package cn.ztr.ymcc.web.controller;

import cn.ztr.ymcc.dto.OrderDto;
import cn.ztr.ymcc.service.ICourseOrderService;
import cn.ztr.ymcc.domain.CourseOrder;
import cn.ztr.ymcc.query.CourseOrderQuery;
import cn.ztr.ymcc.result.JsonResult;
import cn.ztr.ymcc.result.PageList;
import cn.ztr.ymcc.util.AssertUtil;
import cn.ztr.ymcc.utils.LoginContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/courseOrder")
public class CourseOrderController {

    @Autowired
    public ICourseOrderService courseOrderService;

    @Autowired
    private LoginContextUtils loginContextUtils;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
    * 保存和修改公用的
    */
    @PostMapping("/save")
    public JsonResult saveOrUpdate(@RequestBody CourseOrder courseOrder){
        if(courseOrder.getId()!=null){
            courseOrderService.updateById(courseOrder);
        }else{
            courseOrderService.save(courseOrder);
        }
        return JsonResult.me();
    }

    /**
    * 删除对象
    */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        courseOrderService.removeById(id);
        return JsonResult.me();
    }

    /**
   * 获取对象
   */
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable("id")Long id){
        return JsonResult.me().setData(courseOrderService.getById(id));
    }


    /**
    * 查询所有对象
    */
    @GetMapping("/list")
    public JsonResult list(){
        return JsonResult.me().setData(courseOrderService.list(null));
    }


    /**
    * 带条件分页查询数据
    */
    @PostMapping("/pagelist")
    public JsonResult page(@RequestBody CourseOrderQuery query){
        Page<CourseOrder> page = new Page<CourseOrder>(query.getPageNo(), query.getPageSize());
        page = courseOrderService.page(page);
        return JsonResult.me().setData(new PageList<CourseOrder>(page.getTotal(), page.getRecords()));
    }

    /**
     * 普通订单下单
     * @param orderDto
     * @return
     */
    @PostMapping("/placeOrder")
    public JsonResult placeOrder(@RequestBody OrderDto orderDto , HttpServletRequest request) throws Exception {
        //获取用户id
        Long loginId  = loginContextUtils.getUserId(request.getHeader("jwtToken"));
        //检验幂等性
        String token = orderDto.getToken();
        AssertUtil.isTrue(!StringUtils.hasText(token),"非法访问");
        Object o = redisTemplate.opsForValue().get("placeOrder:" + loginId);
        AssertUtil.isTrue(o!=null,"请勿重复下单");
        JsonResult result = courseOrderService.placeOrder(orderDto, loginId);
        //删除redis中的token
        redisTemplate.delete("placeOrder:" + loginId);
        return result;
    }

    /**
     * 获取token,用于检验下单的幂等性
     * @param courseId
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/createToken/{id}")
    public JsonResult createToken(@PathVariable("id")Long courseId,HttpServletRequest request) throws Exception {
        Long loginId = loginContextUtils.getUserId(request.getHeader("jwtToken"));
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("placeOrder:"+loginId,token,10, TimeUnit.MINUTES);
        return JsonResult.me(token);
    }

    /**
     * 秒杀下单
     * @param orderDto
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/killPlaceOrder")
    public JsonResult killPlaceOrder(@RequestBody OrderDto orderDto, HttpServletRequest request) throws Exception {
        //获取用户id
        Long loginId  = loginContextUtils.getUserId(request.getHeader("jwtToken"));
        //检验幂等性
        String token = orderDto.getToken();
        AssertUtil.isTrue(!StringUtils.hasText(token),"非法访问");
        Object o = redisTemplate.opsForValue().get("placeOrder:" + loginId);
        AssertUtil.isTrue(o!=null,"请勿重复下单");
        JsonResult result = courseOrderService.killPlaceOrder(orderDto, loginId);
        //删除redis中的token
        redisTemplate.delete("placeOrder:" + loginId);
        return result;
    }

}
